// pages/order/order.js

import {Cart} from "../../models/cart";
import {Sku} from "../../models/sku";
import {OrderItem} from "../../models/order-item";
import {Order} from "../../models/order";
import {ShoppingWay} from "../../core/enum";

const cart = new Cart()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    finalTotalPrice: 0,
    totalPrice: 0,
    discountMoney: 0,
    submitBtnDisable: false,

    address: null,

    currentCouponId: null,
    order: null,
    isOk: true,

    orderFail: false,
    orderFailMsg: '',

    shoppingWay: ShoppingWay.BUY
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    let orderItems;
    let localItemCount
    const shoppingWay = options.way
    this.data.shoppingWay = shoppingWay

    if (shoppingWay === ShoppingWay.BUY) {
      const skuId = options.sku_id
      const count = options.count
      orderItems = await this.getSingleOrderItems(skuId, count)
      localItemCount = 1
    } else {
      const skuIds = cart.getCheckedSkuIds()
      orderItems = await this.getCartOrderItems(skuIds)
      localItemCount = skuIds.length
    }

    const order = new Order(orderItems, localItemCount)
    this.data.order = order

    try {
      order.checkOrderIsOk()
    } catch (e) {
      console.error(e)
      // this.setData({
      //   isOk: false
      // })
      return
    }

    this.setData({
      orderItems
    })

    // const coupons = await Coupon.getMySelfWithCategory()
    // const couponBOList = this.packageCouponBOList(coupons, order)
    // this.setData({
    //   couponBOList,
    //   totalPrice: order.getTotalPrice(),
    //   finalTotalPrice: order.getTotalPrice()
    // })

  },

  async getCartOrderItems(skuIds) {
    // 同步最新的SKU数据
    const skus = await Sku.getSkusByIds(skuIds)
    const orderItems = this.packageOrderItems(skus)
    return orderItems
  },

  async getSingleOrderItems(skuId, count) {
    const skus = await Sku.getSkusByIds(skuId)
    return [new OrderItem(skus[0], count)];
  },

  packageOrderItems(skus) {
    return skus.map(sku => {
      const count = cart.getSkuCountBySkuId(sku.id)
      return new OrderItem(sku, count)
    })
  },

})